package com.meisen.springboot.controller;

import com.meisen.springboot.entity.UserInfo;
import com.meisen.springboot.response.ResultEntity;
import com.meisen.springboot.util.Result;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/userinfo")
public class UserInfoController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ResultEntity login(UserInfo userInfo){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(userInfo.getUsername(), userInfo.getPassword());
        Map<String, Object> result = new HashMap<>();
        try {
            subject.login(token);
        } catch (IncorrectCredentialsException e) {
            return Result.error(2, "密码错误");
        } catch (LockedAccountException e) {
            return Result.error(2, "登录失败，该用户已被冻结");
        } catch (AuthenticationException e) {
            return Result.error(2, "该用户不存在");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(2, "登录失败，未知错误");
        }
        result.put("token", subject.getSession().getId());
        return Result.success(result, "登录成功");
    }

    @GetMapping("/unauth")
    public ResultEntity unAuth() {
        return Result.error(4, "未登录");
    }
}
